package cn.csg.iotplatform.module.system.controller.admin.user;

import cn.csg.iotplatform.framework.common.constants.GlobalConstants;
import cn.csg.iotplatform.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.csg.iotplatform.framework.common.util.common.ToolUtil;
import cn.csg.iotplatform.framework.datapermission.core.annotation.DataPermission;
import cn.csg.iotplatform.framework.excel.core.vo.ImportResultVO;
import cn.csg.iotplatform.framework.web.core.util.WebFrameworkUtils;
import cn.csg.iotplatform.module.common.annotations.TranslateMethod;
import cn.csg.iotplatform.module.common.util.ExcelImportUtil;
import cn.csg.iotplatform.module.system.annotations.DecryptDesensitization;
import cn.csg.iotplatform.module.system.api.permission.PermissionApi;
import cn.csg.iotplatform.module.system.enums.ErrorCodeConstants;
import cn.csg.iotplatform.module.system.service.user.UserImportValidate;
import cn.csg.iotplatform.framework.common.enums.CommonStatusEnum;
import cn.csg.iotplatform.framework.common.pojo.CommonResult;
import cn.csg.iotplatform.framework.common.pojo.PageParam;
import cn.csg.iotplatform.framework.common.pojo.PageResult;
import cn.csg.iotplatform.framework.excel.core.util.ExcelUtils;
import cn.csg.iotplatform.framework.operatelog.core.annotations.OperateLog;
import cn.csg.iotplatform.module.system.controller.admin.user.vo.user.*;
import cn.csg.iotplatform.module.system.convert.user.UserConvert;
import cn.csg.iotplatform.module.system.dal.dataobject.dept.DeptDO;
import cn.csg.iotplatform.module.system.dal.dataobject.user.AdminUserDO;
import cn.csg.iotplatform.module.system.enums.common.SexEnum;
import cn.csg.iotplatform.module.system.service.dept.DeptService;
import cn.csg.iotplatform.module.system.service.user.AdminUserService;
import cn.hutool.core.date.DateUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static cn.csg.iotplatform.framework.common.pojo.CommonResult.error;
import static cn.csg.iotplatform.framework.common.pojo.CommonResult.success;
import static cn.csg.iotplatform.framework.common.util.collection.CollectionUtils.convertList;
import static cn.csg.iotplatform.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.csg.iotplatform.framework.operatelog.core.enums.OperateTypeEnum.IMPORT;

@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/system/user")
@Validated
@Slf4j
public class UserController {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private ExcelImportUtil excelImportUtil;

    @Resource
    private PermissionApi permissionApi;

    @PostMapping("/create")
    @Operation(summary = "新增用户")
    @PreAuthorize("@ss.hasPermission('systemManagement:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        Long id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("/update")
    @Operation(summary = "修改用户")
    @PreAuthorize("@ss.hasPermission('systemManagement:user:edit')")
    @DecryptDesensitization
    public CommonResult<Boolean> updateUser(@RequestBody UserSaveReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('systemManagement:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @DeleteMapping("/deleteBatch")
    @Operation(summary = "删除用户(批量)")
    @PreAuthorize("@ss.hasPermission('systemManagement:user:delete')")
    public CommonResult<Boolean> deleteBatchUser(@Valid @RequestBody UserDeleteBatchDto dto) {
        userService.deleteBatchUser(dto.getIds());
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "重置用户密码")
    @PreAuthorize("@ss.hasPermission('systemManagement:user:resetPassword')")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改用户状态")
    @PreAuthorize("@ss.hasPermission('systemManagement:user:edit')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户分页列表")
    // @PreAuthorize("@ss.hasPermission('system:user:page:page')")
    public CommonResult<PageResult<UserRespVO>> getUserPage(@Valid UserPageReqVO pageReqVO) {
        PageResult<UserRespVO> result = this.userService.queryUserPage(pageReqVO);
        return success(result);
    }

    @GetMapping("/queryUserDeptRelation")
    @Operation(summary = "获得用户借调单位列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:queryUserDeptRelation')")
    public CommonResult<List<UserDeptRelationVo>> queryUserDeptRelation(@RequestParam("id") Long id) {
        List<UserDeptRelationVo> result = this.userService.queryUserDeptRelation(id);
        return success(result);
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 拼接数据
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(convertList(list, AdminUserDO::getDeptId));
        return success(UserConvert.INSTANCE.convertSimpleList(list, deptMap));
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:get')")
    @TranslateMethod
    public CommonResult<UserRespVO> getUser(@RequestParam("id") Long id) {
        AdminUserDO user = userService.getUser(id);
        // 拼接数据
        DeptDO dept = deptService.getDept(user.getDeptId());
        return success(UserConvert.INSTANCE.convert(user, dept));
    }

    @PostMapping("/export-excel")
    @Operation(summary = "导出用户 Excel")
    @OperateLog(type = EXPORT)
    @PreAuthorize("@ss.hasPermission('systemManagement:user:export')")
    public void exportUserList(@Validated @RequestBody UserPageReqVO exportReqVO, HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AdminUserDO> list = userService.getUserPage(exportReqVO).getList();
        // 输出 Excel
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(convertList(list, AdminUserDO::getDeptId));
        ExcelUtils.write(response, "用户数据.xls", "数据", UserRespVO.class, UserConvert.INSTANCE.convertList(list, deptMap));
    }

    //@GetMapping("/get-import-template")
    //@Operation(summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<UserImportExcelVO> list = Arrays.asList(
                UserImportExcelVO.builder().username("yunai").deptId(1L).email("yunai@iocoder.cn").mobile("15601691300")
                        .nickname("芋道").status(CommonStatusEnum.ENABLE.getStatus()).sex(SexEnum.MALE.getSex()).build(),
                UserImportExcelVO.builder().username("yuanma").deptId(2L).email("yuanma@iocoder.cn").mobile("15601701300")
                        .nickname("源码").status(CommonStatusEnum.DISABLE.getStatus()).sex(SexEnum.FEMALE.getSex()).build()
        );
        // 输出
        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", UserImportExcelVO.class, list);
    }

    @PostMapping("/import-excel")
    @Operation(summary = "导入用户")
    @OperateLog(type = IMPORT)
    @PreAuthorize("@ss.hasPermission('systemManagement:user:import')")
    public CommonResult<ImportResultVO> importExcel(MultipartFile file) throws Exception {
        ImportResultVO resultVO = new ImportResultVO();
        try {
            List<UserImportExcelDto> list = this.excelImportUtil.getDataList(UserImportExcelDto.class, file.getInputStream(), new UserImportValidate(), resultVO,true);
            if (list != null && !list.isEmpty()) {
                //dvDevicePreRegistrationService.batchInsert(list);
                this.userService.batchImport(list);
            }
        } catch (IOException e) {
            log.error("用户-导入异常", e);
        }
        return success(resultVO);
    }

    //@PostMapping("/copy-user-roles")
    //@Operation(summary = "权限复制")
    @PreAuthorize("@ss.hasPermission('system:user:copy-user-roles')")
    public CommonResult<Boolean> copyUserRoles(@Valid @RequestBody CopyUsersRolesDto dto) {
        this.userService.copyUserRoles(dto);
        return success(true);
    }

    @GetMapping("/getUserStat")
    @Operation(summary = "获得用户统计信息")
    public CommonResult<UserStatRespVO> getUserStat(@ParameterObject @Valid UserPageReqVO reqVO) {
        if(reqVO.getDeptId() == null) reqVO.setDeptId(GlobalConstants.TOP_DEPT_ID);
        UserStatRespVO respVO = this.userService.getUserStat(reqVO);
        return success(respVO);
    }

    @GetMapping("/getUserStatDetail")
    @Operation(summary = "获得用户统计详情")
    public CommonResult<PageResult<UserStatDetailRespVO>> getUserStatDetail(@ParameterObject @Valid UserPageReqVO reqVO) {
        if(reqVO.getDeptId() == null) reqVO.setDeptId(GlobalConstants.TOP_DEPT_ID);
        PageResult<UserStatDetailRespVO> pageResult = this.userService.getUserStatDetail(reqVO);
        return success(pageResult);
    }

    @PostMapping("/user-stat-export")
    @Operation(summary = "导出用户统计")
    @OperateLog(type = EXPORT)
//    @PreAuthorize("@ss.hasPermission('systemManagement:user:export')")
    public void exportUserStat(@Validated @RequestBody UserPageReqVO exportReqVO, HttpServletResponse response) throws IOException {
        if(exportReqVO.getDeptId() == null) exportReqVO.setDeptId(GlobalConstants.TOP_DEPT_ID);
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<UserStatDetailRespVO> list = this.userService.getUserStatDetail(exportReqVO).getList();
        ExcelUtils.write(response, "用户统计详情"+ DateUtil.format(DateUtil.date(),"yyyyMMdd") +".xls", "数据", UserStatDetailRespVO.class, list);
    }

    @GetMapping("/getPersonal")
    @Operation(summary = "个人中心用户信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @DataPermission(enable = false)
    @TranslateMethod
    public CommonResult<UserRespVO> getPersonalUser(@RequestParam("id") Long id) {
//        Long userId = WebFrameworkUtils.getLoginUserId();
        UserRespVO userInfo = userService.getUserInfo(id);
//        boolean hasEditPermission = permissionApi.hasAnyPermissions(userId, "systemManagement:user:edit").getCheckedData();
//        if( ! id.equals(userId) && ! hasEditPermission ){//非本人且无权限，按需求对用户信息查看进行限制
//            userInfo.setNickname(ToolUtil.formatStr(1,userInfo.getNickname()));
//            userInfo.setMobile(ToolUtil.formatStr(3,userInfo.getMobile()));
//            userInfo.setEmail(ToolUtil.formatStr(3,userInfo.getEmail()));
//            userInfo.setUserNo(ToolUtil.formatStr(1,userInfo.getUserNo()));
//            userInfo.setELink(ToolUtil.formatStr(1,userInfo.getELink()));
//        }
        return success(userInfo);
    }

    @PutMapping("/updatePersonal")
    @Operation(summary = "个人中心修改用户")
    @DecryptDesensitization
    public CommonResult<Boolean> updatePersonalUser(@RequestBody UserSaveReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @GetMapping("/queryPersonalDeptRelation")
    @Operation(summary = "获得用户借调单位列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @DataPermission(enable = false)
    public CommonResult<List<UserDeptRelationVo>> queryPersonalDeptRelation(@RequestParam("id") Long id) {
        List<UserDeptRelationVo> result = this.userService.queryUserDeptRelation(id);
        return success(result);
    }

    @PostMapping("/getUserAcc")
    public CommonResult<String> getUserAcc() {
        Long userId = WebFrameworkUtils.getLoginUserId();
        log.info("getUserAcc>>>userId={}",userId);
        if(userId == null) return error(GlobalErrorCodeConstants.FORBIDDEN);
        AdminUserDO adminUserDO = userService.getUser(userId);
        if(adminUserDO == null) return error(GlobalErrorCodeConstants.FORBIDDEN);
        return success(adminUserDO.getUsername());
    }

    @GetMapping("/isUpdatePassword")
    public CommonResult<UserFirLoginRespVO> isUpdatePassword() {
        Long userId = WebFrameworkUtils.getLoginUserId();
        return success(userService.isUpdatePassword(userId));
    }
}
